package com.uil.fileutil.utils;

import org.springframework.stereotype.Component;

import java.io.*;
import java.util.*;

/**
 * @author liu
 */
@Component
public class FileTobase64Util {

    public static final String PREFIX = "D:\\桌面文件\\";

    /**
     * 将多个文件生成base64
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static Map<String, String> multipleFileToBase(String filePath) throws IOException {
        File folder = new File(PREFIX + filePath);
        File[] files = folder.listFiles();
        Map<String, String> base64s = new HashMap<>();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String name = file.getName();
                    byte[] bytes = new byte[(int) file.length()];
                    FileInputStream fileInputStream = new FileInputStream(file);
                    fileInputStream.read(bytes);
                    base64s.put(name.substring(0, name.length() - 4), Base64.getEncoder().encodeToString(bytes));
                }
            }
        }
        return base64s;
    }

    /**
     * 将生成的 每一个base64 编码  写到不同的txt文件中
     *
     * @param flie 读取文件路径
     * @throws IOException
     */
    public static void base64ToFile(String flie) throws IOException {
        Map<String, String> map = FileTobase64Util.multipleFileToBase(flie);
        Set<Map.Entry<String, String>> entries = map.entrySet();
        try {
            entries.forEach(entry -> {
                BufferedWriter bw = null;
                try {
                    bw = new BufferedWriter(new FileWriter("D:\\桌面文件\\输出文件夹" + flie + entry.getKey() + ".txt", true));
                    bw.newLine();
                    bw.write(entry.getValue());
                    bw.flush(); //很重要，要不然可能输出的字符串不完整！
                } catch (IOException e) {
                    try {
                        bw.close();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex+"1??????????????");
                    }
                    throw new RuntimeException(e+"2??????????????");
                }
            });

        } catch (Exception e) {
            throw new RuntimeException(e+"3??????????????");
        }
    }




    /**
     * 生成单个base64 编码文件
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public String singleFileToBase(String filePath) throws IOException {
        File file = new File(PREFIX + filePath);
        byte[] bytes = new byte[(int) file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(bytes);
        fileInputStream.close();
        return Base64.getEncoder().encodeToString(bytes);
    }

}
